<template>
  <div class="appeal">
    <back />
    <el-steps :space="200" :active="activeIndex" finish-status="success" align-center>
      <el-step title="填写账号" />
      <el-step title="身份验证 & 设置新密码" />
      <el-step title="完成" />
    </el-steps>
    <el-form
      ref="appealFormRef"
      :model="appealForm"
      :rules="rules"
      class="appeal-form m-t-20"
      label-position="left"
      label-width="100px"
      status-icon
    >
      <el-form-item v-show="activeIndex === 0" prop="username" label="账号：">
        <el-input v-model="appealForm.username" placeholder="请输入公司全称或已核准公司全称" />
      </el-form-item>
      <el-form-item v-show="activeIndex === 1" prop="phone" label="预留手机号：">
        <el-input v-model="appealForm.phone" readonly />
      </el-form-item>
      <el-form-item class="form-item-code" v-show="activeIndex === 1" prop="code" label="验证码：">
        <el-input v-model="appealForm.code" />
        <el-button :disabled="'获取验证码' !== getCodeBtnText" @click.number="getCode">
          {{ getCodeBtnText }}
        </el-button>
      </el-form-item>
      <el-form-item v-show="activeIndex === 1" prop="password1" label="新密码：">
        <el-input v-model="appealForm.password1" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item v-show="activeIndex === 1" prop="password2" label="确认密码：">
        <el-input v-model="appealForm.password2" type="password" placeholder="请输入确认密码" />
      </el-form-item>
    </el-form>
    <el-result
      v-show="activeIndex === 2"
      icon="success"
      title="密码设置成功"
      :sub-title="resultSubTitle"
    >
      <template #extra>
        <el-button @click="toLogin" type="primary">立即跳转到登录页</el-button>
      </template>
    </el-result>
    <div v-show="activeIndex !== 2" class="appeal-footer m-t-20">
      <el-button @click="toNext" :auto-insert-space="false" type="primary">下一步</el-button>
      <el-button v-show="activeIndex !== 0" @click="toLast" :auto-insert-space="false" plain>
        返回
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { AppealForm } from './type';
import { useRouter } from 'vue-router';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import back from '@/components/back/index.vue';
import { verifyUsername, findPWSendCode, alterPassword } from '@/api/login';

/**
 * activeIndex:
 *  0：填写账号
 *  1：身份验证
 *  2： 设置新密码
 *  3： 完成
 */
const activeIndex = ref<number>(0);

// 表单校验
const appealFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  code: [
    {
      validator: validateCode,
      trigger: 'blur',
    },
  ],
  password1: [
    {
      validator: validatePassword1,
      trigger: 'blur',
    },
  ],
  password2: [
    {
      validator: validatePassword2,
      trigger: 'blur',
    },
  ],
});
function validateUsername(rule: any, value: any, callback: any) {
  if (activeIndex.value === 0) {
    if (value === '') callback(new Error('用户名不能为空'));
  }
  callback();
}

function validateCode(rule: any, value: any, callback: any) {
  if (activeIndex.value === 1) {
    if (value === '') callback(new Error('验证码不能为空'));
  }
  callback();
}

function validatePassword1(rule: any, value: any, callback: any) {
  if (activeIndex.value === 1) {
    if (value === '') callback(new Error('密码不能为空'));
  }
  callback();
}

function validatePassword2(rule: any, value: any, callback: any) {
  if (activeIndex.value === 1) {
    if (value === '') callback(new Error('确认密码不能为空'));
    else if (value !== appealForm.password1) callback(new Error('两次输入的密码不一致'));
  }
  callback();
}
const submitForm = (formEl: FormInstance | undefined): Promise<void> => {
  return new Promise((resolve, reject) => {
    formEl?.validate((valid) => {
      if (valid) {
        resolve();
      } else {
        reject();
      }
    });
  });
};

const appealForm: AppealForm = reactive({
  username: '',
  phone: '',
  password1: '',
  password2: '',
  code: '',
});
const resultSubTitle = ref<string>('5秒后自动跳转到登录页');
const phoneBac = ref<string>('');
const toNext = () => {
  // 提交表单，用于校验
  submitForm(appealFormRef.value)
    .then(async () => {
      // 如果为0，则验证账号是否存在
      if (activeIndex.value === 0) {
        const res: any = await verifyUsername(appealForm.username);
        if (res.code === 200) {
          phoneBac.value = res.data;
          appealForm.phone = res.data?.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2');
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
          });
          return;
        }
      }
      // 如果为1，则设置新密码
      if (activeIndex.value === 1) {
        const requestDate = {
          ...appealForm,
          phone: phoneBac.value,
          password: appealForm.password1,
        };
        const res: any = await alterPassword(requestDate);
        if (res.code === 200) {
          ElMessage({
            message: '密码修改成功',
            type: 'success',
          });
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
          });
          return;
        }
      }
      activeIndex.value++;
      // 完成修改密码时所展示的内容
      if (activeIndex.value === 2) {
        let timer: number;
        for (let i = 1; i <= 5; i++) {
          timer = setTimeout(() => {
            resultSubTitle.value = `${5 - i}秒后自动跳转到登录页`;
            if (i === 5) {
              clearTimeout(timer);
              toLogin();
            }
          }, 1000 * i);
        }
      }
    })
    .catch(() => {
      console.log('err');
    });
};
const toLast = () => {
  activeIndex.value--;
};

// 跳转到登录页
const router = useRouter();
const toLogin = () => {
  router.push({
    name: 'login',
  });
};

const getCodeBtnText = ref<string>('获取验证码');
const getCode = () => {
  findPWSendCode(phoneBac.value).then((res: any) => {
    if (res.code === 200) {
      let delay = 60;
      const timer = setInterval(() => {
        delay--;
        getCodeBtnText.value = delay + 's';
        if (delay <= 0) {
          getCodeBtnText.value = '获取验证码';
          clearInterval(timer);
        }
      }, 1000);
    }
  });
};
</script>

<style scoped lang="scss">
.appeal {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  .el-steps {
    width: 100%;
    justify-content: center;
  }
  &-form {
    width: 40%;
    .form-item-code :deep(.el-form-item__content) {
      flex-wrap: nowrap;
    }
  }
  &-footer {
    width: 30%;
    display: flex;
    .el-button {
      flex: 1;
    }
  }
}
</style>
